
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/physics.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart' as sm;
import 'package:ysy_flutter_mvvm_yuanxuan/base/PullPageBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/base/BaseBean.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/base/BaseListDataBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';

typedef LoadCallback = void Function(PullPageBean);

typedef LoadCompleteCallback = BaseListDataBean Function();

typedef LoadBuild<T extends BaseJsonBean>=Widget Function(BuildContext context,List<T> result);

class SmartRefresherWidget<T extends BaseJsonBean> extends StatefulWidget {

  PullDataRefresher<T> valueNotifier=PullDataRefresher(null);
  List<T> data=<T>[];
  PullPageBean? pullPageBean;

  sm.RefreshController controller;
  LoadBuild<T> loadBuild;
  bool enablePullDown;
  bool enablePullUp;
  final LoadCallback? onRefresh;
  final LoadCallback? onLoading;

  bool isShowEmpty=false;

  SmartRefresherWidget({Key? key,
    required this.controller,
    required this.loadBuild,
    required this.valueNotifier,
    this.pullPageBean,
    this.enablePullDown=true,
    this.enablePullUp=false,
    this.isShowEmpty=false,
    this.onRefresh,
    this.onLoading});

  PullPageBean checkPullPageBean(PullPageBean? pullPageBean){
    this.pullPageBean=pullPageBean==null?PullPageBean():pullPageBean;
    return this.pullPageBean!;
  }


  @override
  _SmartRefresherWidgetState createState() => _SmartRefresherWidgetState<T>();
}

class _SmartRefresherWidgetState<T extends BaseJsonBean> extends State<SmartRefresherWidget<T>> {

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      if(widget.onRefresh!=null) widget.onRefresh!(widget.checkPullPageBean(widget.pullPageBean));
    });
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: widget.valueNotifier,
        builder: (BuildContext context, BaseListDataBean<T>? value, Widget? child){
          widget.controller.refreshCompleted();
          widget.controller.loadComplete();
          if(value!=null){
            var pullBean = widget.checkPullPageBean(widget.pullPageBean);
            pullBean.addPage();
            int pageNum=(value.pageNum??0);
            if(pageNum<=1){
              widget.data.clear();
              if(value.result!=null){
                widget.data.addAll(value.result!);
              }
              if(pageNum>=(value.totalPage??0)){
                widget.controller.resetNoData();
              }
            }else{
              if(value.result!=null){
                widget.data.addAll(value.result!);
              }
              if(pageNum>=(value.totalPage??0)){
                widget.controller.loadNoData();
              }
            }
          }

          Widget child;
          if(widget.isShowEmpty){
            child=widget.data.isEmpty?Empty():widget.loadBuild(context,widget.data);
          }else{
            child=widget.loadBuild(context,widget.data);
          }
          return sm.SmartRefresher(
            controller: widget.controller,
            enablePullUp: widget.data.isEmpty?false:widget.enablePullUp,
            enablePullDown: widget.enablePullDown,
            onRefresh: (){
              var pullBean = widget.checkPullPageBean(widget.pullPageBean);
              pullBean.resetPage();
              if(widget.onRefresh!=null) widget.onRefresh!(pullBean);
            },
            onLoading: (){
              var pullBean = widget.checkPullPageBean(widget.pullPageBean);
              if(widget.onLoading!=null) widget.onLoading!(pullBean);
            },
            child: child,
          );
        });
  }
}

class Empty extends StatelessWidget {

  double? imageWidget;
  double? imageHeight;
  String? imageName;

  double? fontSize;
  Color? fontColor;
  String? fontText;

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        height: ScreenUtil.defaultSize.height*0.8,
        alignment: Alignment.center,
        child: Column(
           crossAxisAlignment: CrossAxisAlignment.center,
           mainAxisAlignment: MainAxisAlignment.center,
           children: [
             SizedBox.fromSize(
               size: Size(imageHeight??80.w, imageHeight??80.w),
               child: Image.asset(assetPath(imageName??"ic_empty_kkry.png")),
             ),
             Padding(
                padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
                child: Text(fontText??"暂无数据",style: TextStyle(fontSize: fontSize,color: fontColor),),
             )
           ],
        ),
    );
  }
}


class PullDataRefresher<T extends BaseJsonBean> extends ValueNotifier<BaseListDataBean<T>?>{

  BaseListDataBean<T>? baseListDataBean;

  PullDataRefresher(this.baseListDataBean) : super(baseListDataBean);

  onRefresher(BaseListDataBean<T>? baseListDataBean){
     value=baseListDataBean;
     notifyListeners();
  }
}


class MRefreshConfiguration extends StatelessWidget{
  Widget child;

  MRefreshConfiguration(this.child);

  @override
  Widget build(BuildContext context) {
    return sm.RefreshConfiguration(
        headerBuilder: () => sm.WaterDropHeader(),        // 配置默认头部指示器,假如你每个页面的头部指示器都一样的话,你需要设置这个
        footerBuilder:  () => sm.ClassicFooter(),        // 配置默认底部指示器
        headerTriggerDistance: 80.0,        // 头部触发刷新的越界距离
        springDescription:SpringDescription(stiffness: 170, damping: 16, mass: 1.9),         // 自定义回弹动画,三个属性值意义请查询flutter api
        maxOverScrollExtent :100, //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
        maxUnderScrollExtent:0, // 底部最大可以拖动的范围
        enableScrollWhenRefreshCompleted: true, //这个属性不兼容PageView和TabBarView,如果你特别需要TabBarView左右滑动,你需要把它设置为true
        enableLoadingWhenFailed : true, //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
        hideFooterWhenNotFull: false, // Viewport不满一屏时,禁用上拉加载更多功能
        enableBallisticLoad: true, // 可以通过惯性滑动触发加载更多
        child: child
    );
  }

}


//下拉刷新

// abstract class RefresherWidget extends StatelessWidget {
//
//
//   Widget buildContext(BuildContext context,ScrollController mRefreshController,);
//
//   @override
//   Widget build(BuildContext context) {
//     return buildContext(context,_mScrollController);
//   }
// }
//
//
// abstract class RefresherWidget<T extends BaseJsonBean> extends StatefulWidget {
//
//   bool isEnableLoad=false;
//   bool isCompleteLoad=false;
//
//   LoadCallback? loading;
//   LoadCompleteCallback? loadCompleteCallback;
//   PullPageBean? pullPageBean;
//   ValueNotifier<BaseListDataBean<T>> valueNotifier;
//   LoadStatus _loadStatus=LoadStatus.canRefresh;
//
//   @override
//   _RefresherWidgetState createState() => _RefresherWidgetState();
//
//   Widget buildContext(BuildContext context,ScrollController mRefreshController, List<T>? result);
//
//   RefresherWidget( this.valueNotifier,{this.loading,this.pullPageBean,this.loadCompleteCallback});
// }
//
// class _RefresherWidgetState extends State<RefresherWidget> {
//
//   late ScrollController _mScrollController;
//
//   @override
//   void initState() {
//     super.initState();
//     if(widget.pullPageBean==null)  widget.pullPageBean=PullPageBean();
//     WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
//       widget.loading!(widget.pullPageBean!);
//     });
//     _mScrollController=ScrollController()..addListener(() {
//       if (_mScrollController.position.pixels == _mScrollController.position.maxScrollExtent) {
//          print("  刷新");
//          if(!widget.isEnableLoad  && widget.isCompleteLoad){
//             if(widget.loading != null){
//                 if(widget.pullPageBean==null)  widget.pullPageBean=PullPageBean();
//                 widget.loading!(widget.pullPageBean!);
//                 widget._loadStatus=LoadStatus.refreshing;
//             }
//          }
//       }
//     });
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return ValueListenableBuilder(
//         valueListenable: widget.valueNotifier,
//         builder:( context, BaseListDataBean value,child){
//           if(value.pageNum==value.totalPage){
//               widget._loadStatus=LoadStatus.completed;
//           }else{
//               widget._loadStatus=LoadStatus.canRefresh;
//               widget.pullPageBean?.addPage();
//           }
//           return Container(
//             height: double.infinity,
//             width: double.infinity,
//             child: widget.buildContext(context, _mScrollController,value.result),
//           );
//         },);
//   }
// }
//
// //状态
// enum LoadStatus {
//   canRefresh,
//   refreshing,
//   completed,
//   enable
// }

